package com.itzhouwei.commerce.thread.core.demo4;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:stop的方法 有点等于linux 操作里面 kill指令 它的本质是直接终止线程 如果线程持有某个
 * 对象 还会强制该锁释放 包含临界区 并不安全
 * 例如一个 转账案例  A里面 有100元 转给B 10  B 之前账号100元  如果线程被stop了 那么会导致 A 转出成功  B 没有收到
 * 没有stop 那么是正常的 这种情况会导致出现脏数据情况 所以我说它不是安全的  并且被废弃了 不建议使用
 * @author：zw，微信公共号：yingshengzw
 * @date: 2021/8/28
 * @Copyright：公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、学习、分享、成长，让自己和他人都能有所收获！
 */
public class StopThreadDemo {


        static class TestThread implements Runnable {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.print(i+" ");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        static class TestThreadWithSync implements Runnable {

            @Override
            public void run() {
                synchronized (this) {
                    for (int i = 20; i < 30; i++) {
                        System.out.print(i+" ");
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }


        static class TestThreadWithLock implements Runnable {

            ReentrantLock reentrantLock = new ReentrantLock();

            @Override
            public void run() {
                reentrantLock.lock();
                try {
                    for (int i = 30; i < 40; i++) {
                        System.out.print(i+" ");
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } finally {
                    reentrantLock.unlock();
                }
            }
        }

        public static void main(String[] args) throws InterruptedException {
            Thread testThread = new Thread(new TestThread());
            testThread.start();
            Thread testThreadWithSync = new Thread(new TestThreadWithSync());
            testThreadWithSync.start();
            Thread testThreadWithLock = new Thread(new TestThreadWithLock());
            testThreadWithLock.start();

            Thread.sleep(2000);
            testThread.stop();
            testThreadWithSync.stop();
            testThreadWithLock.stop();

        }
}
